﻿using Common;
using FCT551.Helper;
using FCT551.Models;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Windows;

namespace FCT551.Procedure
{
    public delegate void UpdatestationHandler(int id, string v1, string v2, string v3, bool res);

    /// <summary>
    /// 程序所有的测试方法
    /// </summary>
    public static class TestMethods
    {
        public static UpdatestationHandler? UpdateWorkStation;

        //电压采集卡数据
        public static Dictionary<int, List<double>> VoltageDic;

        //电流采集卡数据
        public static Dictionary<int, List<double>> CurrentDic;

        /// <summary>
        /// 设置所有通道pwm占空比
        /// </summary>
        public static void SetALLPwmValue(ProduceConfigModel produceConfig)
        {
            int value = 100 - produceConfig.PWMValue;
            Global._qjxPwm16.SetALLStation(value);
            Global._qjxPwm4.SetALLStation(value);
        }

        /// <summary>
        /// 关闭pwm输出
        /// </summary>
        /// <param name="produceConfig"></param>
        public static void CloseALLPwmValue(ProduceConfigModel produceConfig)
        {
            int value = 100 - produceConfig.PWMCloseValue;
            Global._qjxPwm16.SetALLStation(value);
            Global._qjxPwm4.SetALLStation(value);
        }

        /// <summary>
        /// 采集电压和电流
        /// </summary>
        public static async Task GetVoltageandCurrent(ProduceConfigModel produceConfig)
        {
            var token = Global._EmgStopTokenSource.Token;
            VoltageDic = new();
            CurrentDic = new();
            //先清空
            Global._ZH44242G14F2_Voltage.ClearRegisterValues();
            Global._ZH44242G14F2_Voltage.ClearRegisterValues();
            Global._ZH44242G14F2_Current.ClearRegisterValues();
            Global._ZH44242G14F2_Current.ClearRegisterValues();
            //采集时间
            await Task.Delay(produceConfig.TimeOut);
            //Stopwatch sw = Stopwatch.StartNew();
            //while (true)
            //{
            //    token.ThrowIfCancellationRequested(); // 检查急停
            //    if (sw.ElapsedMilliseconds > produceConfig.TimeOut) { break; }
            //}
            VoltageDic = Global._ZH44242G14F2_Voltage.RegisterValues;
            CurrentDic = Global._ZH44242G14F2_Current.RegisterValues;
        }

        /// <summary>
        /// 测量转速,通过电压采集卡
        /// </summary>
        public static bool GetRotateSpeedValue(int Station, ProduceConfigModel produceConfig, out double Value)
        {
            var token = Global._EmgStopTokenSource.Token;
            bool Res = true;

            //int v1 = CountCompletePeaks(VoltageDic[Station - 1], 0.001);
            //double time = produceConfig.TimeOut / 1000;
            //转化成多少转每分钟
            //Value = ((v1 / time) + produceConfig.RotateSpeedOffset) * 60;
            //拿到满足满足上下区间电压的个数
            Value = VoltageDic[Station - 1].AsParallel().Where(s => s >= produceConfig.RotateSpeedDown && s <= produceConfig.RotateSpeedUp).ToList().Count;
            return Res = Value >= produceConfig.PWMValueNums ? true : false;
        }

        /// <summary>
        /// 测量电流，通过电流采集卡
        /// </summary>
        public static bool GetCurrentValue(int Station, ProduceConfigModel produceConfig, out double Value)
        {
            var token = Global._EmgStopTokenSource.Token;
            bool Res = true;
            //拿到实时采集的最后一次的电流
            Value = CurrentDic[Station - 1][CurrentDic[Station - 1].Count - 1] + produceConfig.VoltageOffset;
            Res = Value >= produceConfig.VoltageDown && Value <= produceConfig.VoltageUp ? true : false;
            return Res;
        }

        /// <summary>
        /// 把拿到的电压值转化成转速
        /// </summary>
        /// <param name="voltages"></param>
        /// <param name="threshold"></param>
        /// <returns></returns>
        public static int CountCompletePeaks(List<double> voltages, double threshold = 0.1)
        {
            if (voltages.Count < 3) return 0;

            int peakCount = 0;
            bool isRising = false;

            for (int i = 1; i < voltages.Count; i++)
            {
                double delta = voltages[i] - voltages[i - 1];

                if (!isRising && delta > threshold)
                {
                    isRising = true; // 开始上升
                }
                else if (isRising && delta < -threshold)
                {
                    peakCount++;     // 完成一个完整峰谷
                    isRising = false;
                }
                // 忽略微小波动（delta绝对值 < threshold）
            }

            return peakCount;
        }

        /// <summary>
        /// 比较函数,Up是上限，Down是下限，value是要比较的值
        /// </summary>
        /// <param name="ComparisonSign"></param>
        /// <param name="item1"></param>
        /// <param name="item2"></param>
        /// <returns></returns>
        public static bool Rangeitem1Andiem2(string ComparisonSign, double Down, double Up, double value)
        {
            switch (ComparisonSign)
            {
                case "<":
                    if (value < Down)
                    {
                        return true;
                    }
                    return false;

                case ">":
                    if (value > Up)
                    {
                        return true;
                    }
                    return false;

                case "<=":
                    if (value <= Down)
                    {
                        return true;
                    }
                    return false;

                case ">=":
                    if (value >= Up)
                    {
                        return true;
                    }
                    return false;

                case "<>":
                    if (value > Down && value < Up)
                    {
                        return true;
                    }
                    return false;

                case "><":
                    if (value < Down || value > Up)
                    {
                        return true;
                    }
                    return false;

                case "<==>":
                    if (value >= Down && value <= Up)
                    {
                        return true;
                    }
                    return false;

                case "=><=":
                    if (value <= Down || value >= Up)
                    {
                        return true;
                    }
                    return false;

                case "":

                    return false;

                case null:
                    return false;
            }
            return true;
        }
    }
}